<script setup lang="ts">
import { onMounted, ref } from 'vue';

const titles = withDefaults(
  defineProps<{
    title?: string; // 是否必传
  }>(),
  {
    title: '标题'
  }
);

const emits = defineEmits(['close']);

const isShow = ref(true);
const titleDom = ref(null);
const bhastitle = ref(true);
onMounted(() => {
  move(titleDom.value);
  bhastitle.value = titles.title == '' ? false : true;
});

function move(el: any) {
  const parent: any = el.parentElement;
  el.onmousedown = function (e: any) {
    document.onselectstart = function () {
      return false;
    };
    const disx = e.pageX - parent.offsetLeft;
    const disy = e.pageY - parent.offsetTop;
    if (e.preventDefault) {
      e.preventDefault();
    } else {
      e.returnValue = false;
    }
    document.onmousemove = function (e) {
      let left = e.clientX - disx;
      let top = e.clientY - disy;

      if (left <= 0) {
        left = 5; // 设置成5是为了不离边缘太近
      } else if (left > document.documentElement.clientWidth - el.clientWidth) {
        // document.documentElement.clientWidth 屏幕的可视宽度
        left = document.documentElement.clientWidth - el.clientWidth - 5;
      }
      if (top <= 0) {
        top = 5;
      } else if (top > document.documentElement.clientHeight - el.clientHeight) {
        top = document.documentElement.clientHeight - el.clientHeight - 5;
        // console.log(document.documentElement.clientHeight, el.clientHeight)
      }
      parent.style.left = left + 'px';
      parent.style.top = top + 'px';
    };
    document.onmouseup = function () {
      document.onmousemove = document.onmouseup = null;
    };
  };
}

// function stopMove(el: any) {
//   el.onmousedown = function (e: any) {
//     e.stopPropagation();
//   };
// }
</script>

<template>
  <div class="zzdialog" v-if="isShow">
    <div class="zz-dialog-title zzdialog-title" ref="titleDom" v-if="bhastitle">
      <span>{{ title }}</span>
      <span class="zzdialog-close" title="关闭" @click="emits('close', {})">X</span>
    </div>
    <slot />
  </div>
</template>

<style scoped>
.zzdialog {
  position: absolute;
  border: 1px solid rgba(32, 160, 255, 0.6);
  min-width: 50px;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.5);
}

.zzdialog-close {
  position: absolute;
  top: 0px;
  right: 0px;
  cursor: default;
  width: 30px;
  height: 36px;
  text-align: center;
}

.zzdialog-close:hover {
  color: red;
}

.zz-dialog-title {
  background-color: rgba(0, 0, 0, 0.5);
  height: 36x;
  line-height: 36px;
  padding-left: 8px;
  font-size: 14px;
  border-bottom: 1px solid;
  border-image: linear-gradient(90deg, #2e678f 0, #0cf 49%, rgba(22, 54, 103, 0) 100%) 1 1;
  cursor: move;
}
</style>
